Day 29 : 用於生產的 TensorFlow Extended (TFX) 實作
tags: MLOps
- 用於生產的機械學習系統,在 Day 28 介紹 TensorFlow Extended (TFX) 解決方案,是專門用於可擴充的高效能機器學習工作,包括建立模型、進行訓練、提供推論,以及管理線上、行動裝置 (TensorFlow Lite)和網頁應用服務 (TensorFlow JS) 的部署。
- 本日我們修改 TFX 官方在筆記本可執行的互動式範例,透過實作理解 TFX 如何在工作流程中透過組件功能驗證資料、特徵工程、訓練模型、模型分析到部署模型。
- Colab 實作範例
,內容源自TFX 官方範例。
TFX 組件筆記本互動實作
0. 安裝與設置 TFX 環境
-
更新 Colab 的
pip。 -
安裝 TFX,安裝完需重新啟動執行階段(Restart Runtime)
!pip install tfx -
設定工作路徑。
-
下載芝加哥 Taxi Trips 資料集 ,將集構建一個預測小費
tips的模 型。
0. 創建互動文件檢視器 InteractiveContext
tfx.orchestration.experimental.interactive.interactive_context.InteractiveContext允許在 notebook 環境中以互動方式查看 TFX 組件。InteractiveContext預設使用臨時的中繼資料。- 已有自己的 pipeline 可設定
pipe_root參數。 - 已有中繼資料庫可設定
metadata_connection_config參數。
- 已有自己的 pipeline 可設定
- 透過
InteractiveContext()逐一演示互動情形,請留意InteractiveContext.run()是在筆記本互動顯示方式,在生產環境中可專注組件流程(請參閱構建 TFX 管道指南)。
1. ExampleGen
-
ExampleGen將數據拆分為訓練集和評估集(預設為 2/3 訓練 、 1/3 評估) -
ExampleGen將數據轉換為tf.Example格式(參閱說明)。 -
本範例將
_data_root的 CSV 資料集輸入至ExampleGen。example_gen = tfx.components.CsvExampleGen(input_base=_data_root)
context.run(example_gen) -
觀察互動介面內容,建議您使用 Colab 測試,在此介面中:
.execution_id是持續累加的版次編號,在對應的資料夾將各版次的內容留存紀錄。.component指的是該 TFX 組件,譬如下圖顯示為.component.CsvExampleGen。.component.inputs紀錄輸入來源。.component.outputs紀錄輸出結 果。

2. StatisticsGen
-
StatisticsGen組件輸入ExampleGen數據後,將據以計算出資料集的統計數據。 -
StatisticsGen是 TFDV 模組功能之一。statistics_gen = tfx.components.StatisticsGen(
examples = example_gen.outputs['examples']
)
context.run(statistics_gen) -
context.run(statistics_gen)觀察互動介面:.execution_id版次累加至2。.component.inputs組件輸入為Examples。- 輸出為
ExampleStatistics。

-
context.show(statistics_gen.outputs['statistics'])如同 TFDV 工具以 Facets 視覺化統計資訊。context.show(statistics_gen.outputs['statistics'])- 可以觀察判讀可能異常的紅色值、資料分佈情形等。

- 可以觀察判讀可能異常的紅色值、資料分佈情形等。
3. SchemaGen
-
SchemaGen組件會依據您的資料統計自動產生 Schema ,包含數據預期邊界、資料類型與屬性它還使用TensorFlow 數據驗證庫。 -
SchemaGen同樣是 TFDV 模組功能之一。 -
即便 Schema 自動生成已經很實用,但您仍應該會依據需求進行審查和修改。
schema_gen = tfx.components.SchemaGen(
statistics=statistics_gen.outputs['statistics'],
infer_feature_shape=False)
context.run(schema_gen)SchemaGen輸入為StatisticsGen,默認情況下查看已拆分的訓練資料集。SchemaGen輸出為Schema。

SchemaGen執行後可透過context.show(schema_gen.outputs['schema'])查看 Schema 表格。- 表格呈現各特徵名稱、屬性、是否必須、所有值、Domain 及 邊界範圍等, 參見 SchemaGen 文件。


4. ExampleValidator
-
ExampleValidator組件根據 Schema 的預期檢測數據中的異常。 -
ExampleValidator同樣是 TFDV 模組功能之一。 -
ExampleValidator的輸入是來自具有數據統計資訊的StatisticsGen以及具有數據定義 Schema 的SchemaGen。 -
ExampleValidator的輸出anomalies是有無異常的判讀結果。example_validator = tfx.components.ExampleValidator(
statistics = statistics_gen.outputs['statistics'],
schema = schema_gen.outputs['schema'])
context.run(example_validator)-
執行
ExampleValidator後可以產生異常情形的圖表,綠字 No anomalies found. 表示無異常。

context.show(example_validator.outputs['anomalies'])
-
第 13 屆鐵人賽鍊成